/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit
import AFNetworking

//网络请求的枚举类型
enum RequestType: Int {
    //get请求方式
    case GET = 0
    //post请求方式
    case POST = 1
}

//网络请求专用类
class LSNetworkTools: AFHTTPSessionManager {
    
    //闭包的别名
    typealias CallBackType = (response: AnyObject?, error: NSError?)->()
    
    //  单例全局访问点
    static let sharedTools: LSNetworkTools = {
        let tools = LSNetworkTools()
        //  添加响应可接受的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    //MARK: - 封装上传图片接口
    func requestUpload(url: String, params: AnyObject?, imageData: NSData, name: String, callBack: CallBackType) {
        
        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            //data 图片对应的二进制数据
            //name 服务端需要参数
            //fileName 图片对应名字,一般服务不会使用,因为服务端会直接根据你上传的图片随机产生一个唯一的图片名字
            //mimeType 资源类型
            //不确定参数类型 可以这个 octet-stream 类型, 二进制流
            formData.appendPartWithFileData(imageData, name: name, fileName: "test", mimeType: "application/octet-stream")
            
            }, progress: nil, success: { (_, reponse) -> Void in
                callBack(response: reponse, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }
    }
    
    //MARK: - 封装get\post请求
    func request(requestType: RequestType, url: String, params: AnyObject?, callBack: CallBackType) {
        
        if requestType == .GET {

            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
            
        } else {
            
            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        }
    }
}

//MARK: - 发微博相关接口
extension LSNetworkTools {
    
    //上传带有图片的微博接口
    func upload(access_token: String, status: String, image: UIImage, callBack: CallBackType) {
        //准备url
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        //把图片转成二进制数据
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        
        requestUpload(url, params: params, imageData: imageData, name: "pic", callBack: callBack)
//        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
//
//        //  data 图片对应的二进制数据
//        //  name 服务端需要参数
//        //  fileName 图片对应名字,一般服务不会使用,因为服务端会直接根据你上传的图片随机产生一个唯一的图片名字
//        //  mimeType 资源类型
//        formData.appendPartWithFileData(imageData1, name: "pic", fileName: "test", mimeType: "image/jpeg")
//
//        }, progress: nil, success: { (_, response) -> Void in
//
//            callBack(response: response, error: nil)
//
//        }) { (_, error) -> Void in
//            
//            callBack(response: nil, error: error)
//        }
 
    }
    
    //发送文字微博
    func update(access_token: String, status: String, callBack: CallBackType) {
        
        //  准备url
        let url = "https://api.weibo.com/2/statuses/update.json"
        //  准备参数
        let params = [
            "access_token": access_token,
            "status": status
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
    }
}

//MARK: - 首页相关接口
extension LSNetworkTools {
    
    //  获取当前登录用户及其所关注（授权）用户的最新微博
    func requestStatuses(accessToken: String, maxId: Int64 = 0, sinceId: Int64 = 0, callBack: CallBackType) {
        //  准备url
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //  准备参数
        let params = [
            "access_token": accessToken,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        
        let path = url + "?access_token=" + accessToken
        print(path)
        
        request(.GET, url: url, params: params, callBack: callBack)
        
    }
    
}

//MARK: - OAuth登录相关接口
extension LSNetworkTools {
    
    //  通过code获取accesstoken
    //reqeustAccessTokenWithCode
    //reqeustAccessTokenWithCode
    func reqeustAccessTokenWithCode(code: String, callBack: CallBackType) {
        
        //  准备url
        let url = "https://api.weibo.com/oauth2/access_token"
        
        //  准备参数
        let params = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
        
    }
    
    //通过accesstoken和uid获取用户信息
    func requestUserInfo(userAccount: LSUserAccount, callBack: CallBackType) {
        //准备url
        let url = "https://api.weibo.com/2/users/show.json"
        //准备参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        //执行请求
        request(.GET, url: url, params: params, callBack: callBack)
}

}










